<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { ArticleItem } from '@/api/article/types'
import { useI18n } from '@/hooks/web/useI18n'
import { useValidator } from '@/hooks/web/useValidator'
import { IDomEditor } from '@wangeditor/editor'
import { useUserStoreWithOut } from '@/store/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryApi } from '@/api/category'
import { getUsersApi } from '@/api/user'
import { Icon } from '@/components/Icon'

const { required } = useValidator()
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<ArticleItem>>,
    default: () => null
  }
})

const { t } = useI18n()

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const userStore = useUserStoreWithOut()

const schema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('exampleDemo.title'),
    component: 'Input',
    formItemProps: {
      rules: [required()]
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'info',
    label: t('article.info'),
    component: 'Input',
    componentProps: {
      type: 'textarea'
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'imageList',
    component: 'Upload',
    label: `${t('baseDesc.imageList')}`,
    colProps: {
      span: 24
    },
    componentProps: {
      limit: 3,
      action: 'http://127.0.0.1:9527/sapi/article/upload',
      headers: {
        Authentication: userStore.getToken ?? ''
      },
      name: 'file',
      // fileList: ,
      multiple: true,
      listType: 'picture-card',
      onPreview: (uploadFile) => {
        console.log(uploadFile)
      },
      onRemove: (file) => {
        console.log(file)
      },
      beforeRemove: (uploadFile) => {
        return ElMessageBox.confirm(`确定取消上传 ${uploadFile.name}文件 ?`).then(
          () => true,
          () => false
        )
      },
      onExceed: (files, uploadFiles) => {
        ElMessage.warning(`超过最大上传文件数量，您选择了 ${files.length + uploadFiles.length} 个!`)
      },
      slots: {
        default: () => <Icon icon="ep:plus" size={38}></Icon>
        // tip: () => <div class="el-upload__tip">jpg/png files with a size less than 500KB.</div>
      },
      onSuccess: (res: any) => {
        console.log(res)
      }
    }
  },
  {
    field: 'categoryId',
    label: t('article.categoryName'),
    formItemProps: {
      rules: [required()]
    },
    component: 'TreeSelect',
    componentProps: {
      // nodeKey: 'title',
      props: {
        label: 'title',
        value: 'id'
      }
    },
    optionApi: async () => {
      const res = await getCategoryApi({ pageNum: 1, pageSize: 100 })
      return res.data.list
    }
  },
  {
    field: 'teacherId',
    label: t('exampleDemo.author'),
    formItemProps: {
      rules: [required()]
    },
    component: 'TreeSelect',
    componentProps: {
      // nodeKey: 'username',
      props: {
        label: 'username',
        value: 'id'
      }
    },
    optionApi: async () => {
      const res = await getUsersApi({ pageNum: 1, pageSize: 100, role: 3 })
      return res.data.list
    }
  },
  {
    field: 'readNum',
    label: t('article.readNum'),
    component: 'InputNumber',
    colProps: {
      span: 6
    },
    value: Math.floor(Math.random() * 1000)
  },
  {
    field: 'collectNum',
    label: t('article.collectNum'),
    component: 'InputNumber',
    colProps: {
      span: 6
    },
    value: 0
  },
  {
    field: 'content',
    component: 'Editor',
    colProps: {
      span: 24
    },
    componentProps: {
      defaultHtml: '',
      // @ts-ignore
      onChange: (edit: IDomEditor) => {
        setValues({
          content: edit.getHtml()
        })
      }
    },
    label: t('exampleDemo.content')
  }
])

const rules = reactive({
  title: [required()],
  author: [required()],
  content: [required()]
})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    // 处理上传图片地址
    formData.imageList &&
      formData.imageList.length > 0 &&
      (formData.imageList = formData.imageList
        .reduce((paths: string, v: any): string => {
          return (
            paths +
            ',' +
            (v.response ? v.response.data.filePath : v.url.replace('http://127.0.0.1:9527/', ''))
          )
        }, '')
        .substr(1))
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    console.log(currentRow)
    if (!currentRow) return
    setValues(currentRow)
    setSchema([
      {
        field: 'content',
        path: 'componentProps.defaultHtml',
        value: currentRow.content
      }
    ])
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="schema" />
</template>
